/**
 * @description BackupModel Service
 */

 const { BackupModel, WasteInfoModel, StageModel, ReceiveModel, TransportModel } = require('../db/index')
 
 async function addData(params) {
   const result = await BackupModel.create(params)
   const data = result.dataValues
   return data
 }

 async function addWasteInfoFun(params) {
  const result = await WasteInfoModel.create(params)
  const data = result.dataValues
  return data
}
 
 async function addStageInfoFun(params) {
  const result = await StageModel.create(params)
  // 修改WasteInfoModel
  const rs = await WasteInfoModel.update({
    status: '暂存'
  }, {
    where: {
      id: params.package_id
    }
  })
  const data = result.dataValues
  return data
}
 /**
  * 修改用户信息
  * @param {*} param0 要修改的用户信息
  * @param {*} param1 查询条件
  */
 async function updateData(
   params,
   id
 ) {
   // 拼接修改内容
   const updateObj = params
 
   // 拼接查询条件
   const whereOption = {}
   if (id) {
     whereOption.id = id
   }
 
   // 执行修改
   const result = await BackupModel.update(updateObj, {
     where: whereOption
   })
   return result[0] > 0
 }
 
 /**
  * 删除用户
  * @param {string} userid 用户id 
  */
 async function deleteData(id) {
   const result = await BackupModel.destroy({
     where: {
       id
     }
   })
   return result > 0
 }
 async function getWasteInfoFun({ page = 1, pageSize = 10, package_id }) {
   console.log(package_id)
    let whereOption = {}
    if (page < 1) {
      page = 1
    }
    if (package_id) {
      whereOption.id = package_id
    }
    let result = await WasteInfoModel.findAll({
      limit: pageSize,
      offset: (page - 1) * pageSize,
      where: whereOption
    })
    let rs = []
    for (let item of result) {
      let obj = {
        id: item.id,
        archived: item.archived,
        classification: item.classification,
        create_time: item.create_time,
        department: item.department,
        recycle_person_id: item.recycle_person_id,
        recycle_time: item.recycle_time,
        transfer_record_id: item.transfer_record_id,
        weight: item.weight,
      }
      // 处理状态：暂存 异常 已归档 已完成 转运中 待处理
      // 1、是否已处理
      if (item.archived === 1) {
        obj.status = '已归档'
      } else {
        const r = await ReceiveModel.findAll({
          where: {
            package_id: item.id
          }
        })
        if (r.length) {
          if (r[0].receive_weight != item.weight) {
            obj.status = '异常'
          } else {
            obj.status = '已完成'
          } 
        } else {
          if (new Date().getTime() - new Date(item.recycle_time).getTime() > 4 * 86400 * 1000) {
            obj.status = '异常'
          } else {
            // 未完成 查看转运表
            const r2 = await TransportModel.findAll({
              where: {
                package_id: item.id
              }
            })
            if (r2.length) {
              let trans = r2[0]
              if (trans.end_time) {
                obj.status = '待处理'
              } else {
                obj.status = '转运中'
              }
            } else {
              // 表示还未运输
              // 查询暂存表
              const r3 = await StageModel.findAll({
                where: {
                  package_id: item.id
                }
              })
              if (r3.length) {
                if (r3[0].receive_weight != item.weight) {
                  obj.status = '异常'
                } else {
                  obj.status = '暂存'
                }
              } else {
                // 标识刚入库  还未暂存
                obj.status = ''
              }
            }
          }
        }
      }
      
      rs.push(obj)
    }
   return rs
 }
 async function getStageInfoFun({package_id}) {
  let whereOption = {}
   if (package_id) {
    whereOption.package_id = package_id
   }
  let result = await StageModel.findAll({
    where: whereOption
  })
  return result
}

async function getReceiveInfoFun({package_id}) {
  let whereOption = {}
   if (package_id) {
    whereOption.package_id = package_id
   }
  let result = await ReceiveModel.findAll({
    where: whereOption
  })
  return result
}
 
async function updateStageInfoFun(
  params,
  id
) {
  // 拼接修改内容
  const updateObj = params

  // 拼接查询条件
  const whereOption = {}
  if (id) {
    whereOption.id = id
  }

  // 执行修改
  const result = await StageModel.update(updateObj, {
    where: whereOption
  })
  return result[0] > 0
}
async function updateWasteInfoFun(
  params,
  id
) {
  // 拼接修改内容
  const updateObj = params

  // 拼接查询条件
  const whereOption = {}
  if (id) {
    whereOption.id = id
  }

  // 执行修改
  const result = await WasteInfoModel.update(updateObj, {
    where: whereOption
  })
  return result[0] > 0
}

async function addTransInfoFun(params) {
  const result = await TransportModel.create(params)
  // 修改WasteInfoModel
  const rs = await WasteInfoModel.update({
    status: '运出'
  }, {
    where: {
      id: params.package_id
    }
  })
  const data = result.dataValues
  return data
}
async function addHandleFun(params) {
  const whereOption = {
    package_id: params.package_id
  }
  let one = await ReceiveModel.findAll({
    where: whereOption
  })
  if (one.length) {
    return {
      code: 500,
      msg: '该包裹已被处理'
    }
  }
  const result = await ReceiveModel.create(params)
  // 修改WasteInfoModel
  const rs = await WasteInfoModel.update({
    status: '处理'
  }, {
    where: {
      id: params.package_id
    }
  })
  const data = result.dataValues
  return data
}

// 通过包裹id查询其生命周期
async function getPackageTimelineFun(params) {
  const {package_id, status} = params
  let result = {}
  if (!status) {
    return {
      code: 500,
      msg: '该包裹暂未处理'
    }
  } else {
    if (status === '暂存') {
      // 查询暂存的信息
      const rs = await StageModel.findAll({
        where: {
          package_id
        }
      })
      result.stage = rs
    }
    if (status === '转运') {
      // 查询暂存的信息
      const rs1 = await StageModel.findAll({
        where: {
          package_id
        }
      })
      result.stage = rs1
      const rs2 = await TransportModel.findAll({
        where: {
          package_id
        }
      })
      result.transport = rs2
    }
    if (status === '处理') {
      // 查询暂存的信息
      const rs1 = await StageModel.findAll({
        where: {
          package_id
        }
      })
      result.stage = rs1
      const rs2 = await TransportModel.findAll({
        where: {
          package_id
        }
      })
      result.transport = rs2
      const rs3 = await ReceiveModel.findAll({
        where: {
          package_id
        }
      })
      result.handle = rs3
    }
    return result
  }
}

// 获取重量异常的包裹
async function getWeightAbmormalFun() {
  // 1、查询所有包裹
  const all = await WasteInfoModel.findAll()
  let arr = []
  for (let item of all) {
    if (item.archived != 1) {
      let weight = item.weight
      const rs = await StageModel.findAll({
        where: {
          package_id: item.id
        }
      })
      if (rs.length) {
        let weightS = rs[0].receive_weight
        if (weight !== weightS) {
          arr.push({
            package_id: item.id,
            status: item.status,
            content: '暂存接收重量异常'
          })
        } else {
          const rs2 = await ReceiveModel.findAll({
            where: {
              package_id: item.id
            }
          })
          if (rs2.length) {
            let weightR = rs2[0].receive_weight
            if (weight !== weightR) {
              arr.push({
                package_id: item.id,
                status: item.status,
                content: '处理站接收重量异常'
              })
            }
          }
        }
      }
    }
  }
  return arr
}




 module.exports = {
  addData,
   updateData,
   deleteData,
   getWasteInfoFun,
   getStageInfoFun,
   getReceiveInfoFun,
   addStageInfoFun,
   addWasteInfoFun,
   updateStageInfoFun,
   addTransInfoFun,
   addHandleFun,
   getPackageTimelineFun,
   getWeightAbmormalFun,
   updateWasteInfoFun
 }
 